package com.kamistoat.ruoyi.ruoyimodulessystem.service.impl;

import com.kamistoat.ruoyi.ruoyiapisystem.domain.SysDictData;
import com.kamistoat.ruoyi.ruoyiapisystem.entity.SysDictTypeEntity;
import com.kamistoat.ruoyi.ruoyicommoncore.constant.UserConstants;
import com.kamistoat.ruoyi.ruoyicommoncore.exception.ServiceException;
import com.kamistoat.ruoyi.ruoyicommoncore.utils.StringUtils;
import com.kamistoat.ruoyi.ruoyicommoncore.utils.page.Query;
import com.kamistoat.ruoyi.ruoyicommonsecurity.utils.DictUtils;
import com.kamistoat.ruoyi.ruoyimodulessystem.service.SysDictDataService;
import com.kamistoat.ruoyi.ruoyimodulessystem.service.SysDictTypeService;
import com.kamistoat.ruoyi.ruoyimodulessystem.dao.SysDictDataDao;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kamistoat.ruoyi.ruoyicommoncore.utils.page.PageUtils;
import com.kamistoat.ruoyi.ruoyiapisystem.entity.SysDictDataEntity;


@Service("sysDictDataService")
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataDao, SysDictDataEntity> implements SysDictDataService {

    @Autowired
    DictUtils dictUtils;
    @Autowired
    SysDictTypeService sysDictTypeService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysDictDataEntity> page = this.page(
                new Query<SysDictDataEntity>().getPage(params),
                new QueryWrapper<SysDictDataEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SysDictDataEntity> selectDictDataList(SysDictData sysDictData) {
        QueryWrapper<SysDictDataEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(sysDictData.getDictType())) {
            queryWrapper.eq("dict_type", sysDictData.getDictType());
        }
        if (StringUtils.isNotEmpty(sysDictData.getDictLabel())) {
            queryWrapper.eq("dict_label", sysDictData.getDictLabel());
        }
        if (StringUtils.isNotEmpty((String) sysDictData.getParams().get("beginTime"))) {
            queryWrapper.ge("create_time", sysDictData.getParams().get("beginTime"));
        }
        if (StringUtils.isNotEmpty((String) sysDictData.getParams().get("endTime"))) {
            queryWrapper.le("create_time", sysDictData.getParams().get("endTime"));
        }
        queryWrapper.orderByAsc("dict_sort");

        return this.list(queryWrapper);
    }

    /**
     * 根据字典类型进行查询并入缓存
     */
    @Override
    public List<SysDictDataEntity> selectDictDataByTypeAndCache(String dictType) {
        List<SysDictDataEntity> dictCache = dictUtils.getDictCache(dictType);
        if (StringUtils.isNotNull(dictCache)) {
            return dictCache;
        }

        List<SysDictDataEntity> sysDictDataEntityList = this.list(
                new QueryWrapper<SysDictDataEntity>()
                        .eq("dict_type", dictType)
                        .eq("status", UserConstants.DICT_NORMAL));

        if (StringUtils.isNotNull(sysDictDataEntityList)) {
            dictUtils.setDictCache(dictType, sysDictDataEntityList);
        }

        return sysDictDataEntityList;
    }

    /**
     * 新增新的字典数据，并更新对应的字典类型缓存
     */
    @Override
    public boolean insertDictDataAndCache(SysDictDataEntity sysDictDataEntity) {
        SysDictTypeEntity dict_type = sysDictTypeService.getOne(
                new QueryWrapper<SysDictTypeEntity>()
                        .select("dict_type")
                        .eq("dict_type", sysDictDataEntity.getDictType()));
        if (StringUtils.isNull(dict_type)) {
            throw new ServiceException("字典数据类型'" + dict_type.getDictType() + "'尚未创建，你不能向其中添加新数据");
        }
        boolean save = this.save(sysDictDataEntity);
        // 更新缓存
        if (save) {
            List<SysDictDataEntity> sysDictDataEntityList = this.selectDictDataByTypeAndCache(sysDictDataEntity.getDictType());
            dictUtils.setDictCache(sysDictDataEntity.getDictType(), sysDictDataEntityList);
        }
        return save;
    }

    /**
     * 修改字典数据，并更新对应的字典类型缓存
     */
    @Override
    public boolean updateDictDataAndCache(SysDictDataEntity sysDictDataEntity) {
        SysDictTypeEntity dict_type = sysDictTypeService.getOne(
                new QueryWrapper<SysDictTypeEntity>()
                        .select("dict_type")
                        .eq("dict_type", sysDictDataEntity.getDictType()));
        if (StringUtils.isNull(dict_type)) {
            throw new ServiceException("字典数据类型'" + dict_type.getDictType() + "'尚未创建，你不能向其中添加新数据");
        }
        boolean updateById = this.updateById(sysDictDataEntity);
        // 更新缓存
        if (updateById) {
            List<SysDictDataEntity> sysDictDataEntityList = this.selectDictDataByTypeAndCache(sysDictDataEntity.getDictType());
            dictUtils.setDictCache(sysDictDataEntity.getDictType(), sysDictDataEntityList);
        }
        return updateById;
    }

    /**
     * 删除字典数据并更新缓存
     */
    @Override
    public boolean deleteDictDataByIdsAndRemoveCache(Long[] dictCodes) {
        Set<String> cacheTypes = new LinkedHashSet<>();
        for (Long dictCode : dictCodes) {
            cacheTypes.add(
                    this.getOne(new QueryWrapper<SysDictDataEntity>()
                            .select("dict_type")
                            .eq("dict_code", dictCode)).getDictType());
        }
        dictUtils.removeDictCache(cacheTypes);
        return this.removeByIds(Arrays.asList(dictCodes));
    }

}